package com.bdc.memory.dao.impl;

import com.bdc.memory.dao.ITagDao;
import com.bdc.memory.domain.TagInfo;
import com.google.inject.Inject;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * User: shawn
 * Date: 2011-6-20
 * Time: 20:54:27
 */
public class ITagDaoImpl implements ITagDao {

    @Inject
    private EntityManager em;

    public void addTag(TagInfo tagInfo) {
        em.persist(tagInfo);
    }

    public void delTag(long tagId) {
        TagInfo tagInfo = em.find(TagInfo.class, tagId);
        em.remove(tagInfo);
    }

    public TagInfo getTag(long tagId) {
        return em.find(TagInfo.class, tagId);
    }

    public TagInfo getTag(long userId, String tag) {
        Query query = em.createNativeQuery("SELECT * FROM tag WHERE userId=? AND tag=?", TagInfo.class);
        query.setParameter(1, userId);
        query.setParameter(2, tag);
        List list = query.getResultList();
        return list.size() == 0 ? null : (TagInfo) list.get(0);
    }

    public List<TagInfo> getTagList(long userId) {
        Query query = em.createNativeQuery("SELECT * FROM tag WHERE userId=?", TagInfo.class);
        query.setParameter(1, userId);
        return query.getResultList();
    }

    public void addTagAmount(long userId, String tag) {
        TagInfo tagInfo = this.getTag(userId, tag);

        if (tagInfo == null) {
            tagInfo = new TagInfo(userId, tag);
            this.addTag(tagInfo);
            tagInfo.setAmount(1);
        }
        else {
            long amount = tagInfo.getAmount() + 1;
            tagInfo.setAmount(amount);
        }
    }

    public void subTagAmount(long userId, String tag) {
        TagInfo tagInfo = this.getTag(userId, tag);

        if (tagInfo != null) {
            long amount = tagInfo.getAmount() - 1;
            tagInfo.setAmount(amount);
        }
    }
}
